<template>
  <div class="add-wrapper">
    <el-page-header @back="goBack" :content="isAdd ? '创建物料' : '编辑物料'">
    </el-page-header>
    <div class="form-wrapper">
      <div class="top-form">
        <div class="descLabel">基本信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item prop="username" label="物料编号">
            <el-input v-model="dataForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="物料名称">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="specifications_model" label="规格型号">
            <el-input v-model="dataForm.specifications_model"></el-input>
          </el-form-item>
          <el-form-item prop="material_type" label="物料类别">
            <ren-select
              v-model="dataForm.material_type"
              dict-type="material_type"
              placeholder="请选择"
            ></ren-select>
          </el-form-item>
          <el-form-item prop="material_attr" label="物料属性">
            <ren-select
              v-model="dataForm.material_attr"
              dict-type="material_attr"
              placeholder="请选择"
            ></ren-select>
          </el-form-item>
          <el-form-item class="is-required" label="产品图片">
            <el-upload
              v-if="fileList.length <= 10"
              class="upload-demo"
              ref="upload"
              action=""
              :auto-upload="false"
              :file-list="fileList"
              :limit="10"
              :on-change="handleUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              list-type="picture-card"
              name="pic"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <div class="picDes">
              <div>上传说明：</div>
              <div>1.格式限制：JNG、PNG、JPEG</div>
              <div>2.大小限制：每张图片大小为10M以内，尺寸建议200*200</div>
              <div>
                3.最多可以上传10张图片，第一张将默认为主图，用于封面展示
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div style="margin-bottom: 36px">
          <el-button @click="goBack" style="margin-left: 35%; margin-top: 36px"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="dataFormSubmitHandle()"
            style="margin-left: 21px"
            >确定</el-button
          >
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="查看">
      <img width="100%" :src="dialogImageUrl" class="avatar" />
    </el-dialog>
  </div>
</template>
  
  <script>
import debounce from "lodash/debounce";
import cloneDeep from "lodash/cloneDeep";
import { isEmail, isMobile } from "@/utils/validate";
import { jsonObjToFormObj } from "@/utils";
import { selfUpload, getMaterialDetail, addMaterial } from "@/api";
export default {
  data() {
    return {
      visible: false,
      roleList: [],
      roleIdListDefault: [],
      dataForm: {
        id: "",
        name: "",
        specifications_model: "",
        material_type: "",
        material_attr: "",
      },
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      isAdd: true,
    };
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: "必填项不能为空",
            trigger: "blur",
          },
        ],
        specifications_model: [
          {
            required: true,
            message: "必填项不能为空",
            trigger: "blur",
          },
        ],
        material_type: [
          {
            required: true,
            message: "必选项不能为空",
            trigger: "change",
          },
        ],
        material_attr: [
          {
            required: true,
            message: "必选项不能为空",
            trigger: "change",
          },
        ],
      };
    },
  },
  activated() {
    this.$refs["dataForm"].resetFields();
    this.fileList = [];
    this.isAdd = true;
    const id = this.$route.params.id;
    this.dataForm.id = id;
    if (id) {
      this.fetchDetail(id);
      this.isAdd = false;
    }
  },
  methods: {
    async fetchDetail(id) {
      const params = {
        id,
      };
      const res = await getMaterialDetail(params);
      console.log(res);
      if (res?.status === 1) {
        const data = res?.data || {};
        this.dataForm = data;
        const pics = data?.pics;
        if (pics.length > 0) {
          const arr = [];
          pics.forEach((item) => {
            arr.push({ name: "", url: item || "" });
          });
          this.fileList = arr;
        }
      }
    },
    async handleUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传图片大小不能超过 10MB!");
        this.$refs.upload.clearFiles();
        this.$refs["dataForm"].resetFields();
        return;
      }
      const params = {};
      params.file = file.raw;
      const formData = jsonObjToFormObj(params);
      const res = await selfUpload(formData);
      if (res?.status === 1) {
        this.$message({
          message: res.msg,
          type: "success",
          duration: "1000",
        });
        this.fileList.push({
          url: res?.url || "",
          uid: file.uid,
        });
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      console.log(this.fileList);
      this.fileList.map((item, index) => {
        if (item.uid == file.uid) {
          this.fileList.splice(index, 1);
        }
      });
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate(async (valid) => {
          if (!valid) {
            return false;
          }
          const params = { ...this.dataForm };
          const arr = [];
          if (this.fileList.length > 0) {
            this.fileList.forEach((item) => arr.push(item.url));
          }
          params.pics = arr;
          params.id = this.dataForm.id ? this.dataForm.id : 0;
          const res = await addMaterial(params);
          if (res?.status === 1) {
            this.$message.success(res?.msg || "操作成功");
            this.$refs.upload.clearFiles();
            this.$refs["dataForm"].resetFields();
            this.fileList = [];
            this.$router.go(-1);
          }
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
  // watch: {
  //   'dataForm.type' (val) {
  //     this.$refs['dataForm'].clearValidate()
  //   }
  // },
};
</script>
  
  <style lang="scss" scoped>
.add-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }

  .form-wrapper {
    ::v-deep .el-select {
      width: 100%;
    }

    .top-form {
      width: 50%;
      margin-top: 36px;

      .picDes {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
        line-height: 18px;
      }
    }
  }
}
</style>
  